// pages/pickUpGoods/pickUpGoods.js
import deliveryApi from '../../service/deliveryApi'
import { checkPhone } from '../../utils/util'
import { $wuxLoading } from '../../components/wux/index'
const app = getApp()
let codeConfig = app.globalData.codeConfig

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsName: '',
    goodsCount: 1,
    data: {
      goodsId: '',
      quantity: '',
      userName: '',
      telephone: '',
      deliveryAddress: ''
    },
    disabled: true,
    pickLoading: false, // 按钮文字前的loading
    deliveryId: '',
    timeoutParam: null, // 轮询计时器
    timeOutLimit: 0, // 超时计时器：20s
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.$wuxLoading = $wuxLoading()
    that.setData({
      "data.goodsId": options.goodsId,
      goodsName: options.goodsName,
      goodsCount: options.goodsCount - 0
    })
  },

  getQuantity (e) {
    this.setData({
      'data.quantity': e.detail.value
    })
    this.canClick()
  },
  getUserName (e) {
    this.setData({
      'data.userName': e.detail.value
    })
    this.canClick()
  },
  getTelephone (e) {
    this.setData({
      'data.telephone': e.detail.value
    })
    this.canClick()
  },
  getDeliveryAddress (e) {
    this.setData({
      'data.deliveryAddress': e.detail.value
    })
    this.canClick()
  },
  // 提货按钮活性控制
  canClick () {
    var quantity = this.data.data.quantity
    var userName = this.data.data.userName
    var telephone = this.data.data.telephone
    var deliveryAddress = this.data.data.deliveryAddress
    if (quantity !== '' && userName !== '' && telephone !== '' && deliveryAddress !== '') {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
  },
  // 提货
  formSubmit(e) {
    var that = this
    var _form = that.data.data
    // 校验表单
    if (_form.quantity - 0 > that.data.goodsCount){
      wx.showToast({
        title: '超过提货数量',
        icon: 'none'
      })
      return false
    } else if (!checkPhone(_form.telephone)){
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return false
    }
    var params = {..._form}
    if (that.data.pickLoading) return
    that.setData({
      pickLoading: true
    })
    deliveryApi.putDelivery(params).then(({data}) => {
      // wx.showLoading({
      //   title: '加载中...',
      // })
      that.$wuxLoading.show({ text: '加载中...' })
      that.setData({
        pickLoading: false
      })
      if (data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        that.setData({
          deliveryId: data.data.deliveryId
        })
        // 修改可提货数量
        that.setData({
          goodsCount: that.data.goodsCount - _form.quantity
        })
        // 提货基本信息添加到缓存中，方便下次直接自动填写
        wx.setStorage({
          key: "userName",
          data: _form.userName
        })
        wx.setStorage({
          key: "telephone",
          data: _form.telephone
        })
        wx.setStorage({
          key: "deliveryAddress",
          data: _form.deliveryAddress
        })
        that.handlePoll()
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        })
      }
    }).catch((res) => {
      that.$wuxLoading.hide()
      that.setData({
        pickLoading: false
      })
    })
  },

  // 轮询，等待上链成功
  handlePoll () {
    var that = this
    if (that.data.timeOutLimit < 20) {
      that.setData({
        timeoutParam: setTimeout(that.statusDelivery, 2000)
      })
    } else {
      wx.showToast({
        title: '提货超时',
        icon: 'none'
      })
      that.$wuxLoading.hide()
      that.setData({
        timeOutLimit: 0,
        timeoutParam: null
      })
    }
  },
  
  // 检查提货状态 
  statusDelivery () {
    var that = this
    var params = {
      deliveryId: this.data.deliveryId
    }
    that.setData({
      timeOutLimit: that.data.timeOutLimit + 1
    })
    deliveryApi.statusDelivery(params).then(({ data }) => {
      if (data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        // 提货状态 1-提货申请中; 2-成功; 3-失败
        if (data.data.deliveryStatus === '1') {
          that.handlePoll()
        } else if (data.data.deliveryStatus === '2') {
          that.setData({
            timeOutLimit: 0,
            timeoutParam: null
          })
          that.$wuxLoading.hide()
          wx.reLaunch({
            url: '../couponBag/couponBag?tipMsg=true'
          })
        } else {
          wx.showToast({
            title: '提货失败',
            icon: 'none'
          })
          that.setData({
            timeOutLimit: 0,
            timeoutParam: null
          })
          that.$wuxLoading.hide()
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    wx.getStorage({
      key: 'userName',
      success(res) {
        that.setData({
          "data.userName": res.data
        })
      }
    })
    wx.getStorage({
      key: 'telephone',
      success(res) {
        that.setData({
          "data.telephone": res.data
        })
      }
    })
    wx.getStorage({
      key: 'deliveryAddress',
      success(res) {
        that.setData({
          "data.deliveryAddress": res.data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }

})